<?php

namespace app\admin\controller\lighting;

use app\common\controller\Backend;
use Throwable;
use app\admin\model\LightingControl;
use ball\JinyeLightIot;
/**
 * 照明控制
 */
class Control extends Backend
{
    /**
     * Control模型对象
     * @var object
     * @phpstan-var \app\admin\model\lighting\Control
     */
    protected object $model;

    protected string|array $defaultSortField = 'id,asc';

    protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected string|array $quickSearchField = ['title', 'id'];

    public function initialize(): void
    {
        parent::initialize();
        $this->getLightIot();
        $this->model = new \app\admin\model\LightingControl();
    }
    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 编辑
     * @throws Throwable
     */
    public function edit(): void
    {
        $pk  = $this->model->getPk();
        $id  = $this->request->param($pk);
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $data[$pk] = $row[$pk];
                        $validate->check($data);
                    }
                }
                if(isset($data['opened'])){
                    $data['is_artificial'] = $data['opened'] +1;
                }
                $JLIot = new JinyeLightIot();
                $JLIot->channelSwitch($row->channel,$row->rtu_addr,$data['opened'] == '1'?'ON':'OFF');
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $this->success('', [
            'row' => $row
        ]);
    }

    /**
     * 批量更新灯控
     */
    protected function getLightIot(){
        $JLIot = new JinyeLightIot();
        $rtulist = get_sys_config('rtulist');
        foreach ($rtulist as $key => $value) {
            $rtudata = $JLIot->channels($value['key']);
            if($rtudata !== false){
                foreach ($rtudata as $k => $v) {
                    $updateData=[
                        'id'=>$v['id'],
                        'title'=>($value['value']-3)*8+$v['channel']."路灯控",
                        'channel'=>$v['channel'],
                        'rtu_id'=>$value['key'],
                        'rtu_addr'=>$value['value'],
                        'opened'=>$v['opened']?1:0,
                    ];
                    if(empty(LightingControl::find($v['id']))){
                        LightingControl::create($updateData);
                    }else{
                        LightingControl::update($updateData);
                    }
                    
                }
            }
        }
    }
}